<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>AuBlog editor</title>
<link rel="stylesheet" type="text/css" href="markitup/images/style.css" />
<!-- jQuery -->
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
<!-- markItUp! -->
<script type="text/javascript" src="markitup/markitup/jquery.markitup.js"></script>
<!-- markItUp! toolbar settings -->
<script type="text/javascript" src="markitup/markitup/sets/default/set.js"></script>
<!-- markItUp! skin -->
<link rel="stylesheet" type="text/css" href="markitup/markitup/skins/markitup/style.css" />
<!--  markItUp! toolbar skin -->
<link rel="stylesheet" type="text/css" href="markitup/markitup/sets/default/style.css" />

<style>
#container {
    position: relative;
}




</style>
<script>
$(function() {
    $(this.textBox)
        .change(autoSize)
        .keydown(autoSize)
        .keyup(autoSize);
 autoSize();
});

function autoSize() {
    // Copy textarea contents; browser will calculate correct height of copy,
    // which will make overall container taller, which will make textarea taller.
 var text = $("#markItUp").val().replace(/\n/g, '<br/>');
    $("#textCopy").html(text);
}
</script>

</head>
<body>
<script type="text/javascript">
<!--
$(document).ready(function()	{
	document.getElementById('playButton').style.visibility='hidden'; // hide play button
	document.getElementById('importButton').style.visibility='hidden'; // hide import button
	checkRecordingNow();
	fillFromAndroidActivity();
	// Add markItUp! to your textarea in one line
	// $('textarea').markItUp( { Settings }, { OptionalExtraSettings } );
	$('#markItUp').markItUp(mySettings);
	
	// You can add content from anywhere in your page
	// $.markItUp( { Settings } );	
	$('.add').click(function() {
 		$.markItUp( { 	openWith:'<opening tag>',
						closeWith:'<\/closing tag>',
						placeHolder:"New content"
					}
				);
 		return false;
	});
	
	// And you can add/remove markItUp! whenever you want
	// $(textarea).markItUpRemove();
	$('.toggle').click(function() {
		if ($("#markItUp.markItUpEditor").length === 1) {
 			$("#markItUp").markItUpRemove();
			$("span", this).text("get markItUp! back");
		} else {
			$('#markItUp').markItUp(mySettings);
			$("span", this).text("remove markItUp!");
		}
 		return false;
	});
	//http://stackoverflow.com/questions/168963/stop-jquery-load-response-from-being-cached
	//http://api.jquery.com/jQuery.ajax
	/* $.ajaxSetup ({
	    // Disable caching of AJAX responses
	    cache: false
	}); */
	queryServerIfTranscriptionIsReady();
	
});
-->
</script>
<!-- <p>Click <a href="#" class="add">this link to insert content</a> from anywhere in the page or 
<a href="#" class="toggle">this one to <span>remove markItUp!</span></a></p>-->
<p>
<span id="buttonArea">
<input type="button"  id="saveButton"  value="Save" onClick="saveButton()" />
<input type="button"  id="publishButton"  value="Publish" onClick="publishPostToDB()" />
<input type="button"  id="deleteButton"  value="Delete" onClick="deletePost()" />
<input type="button"  id="recordButton" value="Record Dictation" onClick="startStopRecordingController()" />
<input type="button"  id="playButton" value="Play" onClick="playPauseAudioController()" />
<input type="button"  id="importButton" value="Transcription" onClick="promptUserImportTranscription()" />
</span>
<script type="text/javascript">
	//http://stackoverflow.com/questions/2314886/how-can-i-debug-javascript-on-android
	console.error('1');
	console.info('2');
	console.log('3');
	console.warn('4');
	
	var hasAudio = false;
	var freshTranscription = false;
	
    function startStopRecordingController() {
    	if(document.getElementById('recordButton').value=="Stop Dictation"){
    		//If the button says stop, stop and simulate save to db
    		var messageResult = Android.stopRecordJS();
    		document.getElementById('markItUp').value = messageResult + document.getElementById('markItUp').value;
    		document.getElementById('recordButton').value="New Dictation";
    		savePostToState(); //Any text changes made durring the recording will be saved with the recording.
    		//Android.preparePlayerJS(); //set up the medial player with the current value of the audio file. this wasnt workign because the service hadnt saved the file completely before showing the button.
    		//right now the media player is only prepared if hte user clicks on the play button. 
    		displayPlayButton();
    		/*todo, add a timer to find out if there is a transcription ready once every minute?
    		Android.downloadTranscriptionFromServerJS(); */
    	}else{
    		//If the button says something else, record
    		Android.saveDaughterForRecordingJS(document.getElementById('f-title').value,document.getElementById('markItUp').value,document.getElementById('post-labels').value);
    		/*
    		1. save what the user sees to this post.
    		*/
    		//savePostToState(); //so that the title of the audio file will correspond with the current title in the javascript
    		/*
    		2. create a new daughter post with the same content 
    		so that the edits teh user makes between turning on the recording 
    		and stopping the reocording go with the recording. 
    		*/
    		//savePostToDB(); //each audio file corresponds to save operation, and most often a daughter entry. Any text changes made durring the recording will be saevd with the recording.
    		/*
    		3. start the recording
    		*/
    		Android.startToRecordJS(document.getElementById('f-title').value);
	    	document.getElementById('recordButton').value="Stop Dictation";
	    	
    	}
    }
    
    /*
    This function is largely controlled by the MediaPlayer in the Android logic, 
    so it only recieves the value of the button from Android. The audio is played in a loop.
    a. if audio is playing, hitting the button will pause it.
    b. if audio is not playing, hitting the button wil play it. 
    */
    function playPauseAudioController(){
    	if(document.getElementById('playButton').value=="Pause"){
    		//pause
    		document.getElementById('playButton').value=Android.playOrPauseAudioJS();
    	}else{
    		//play
    		document.getElementById('playButton').value=Android.playOrPauseAudioJS();
    	}
    }
    
    /*
    There are three states of transcription:
    	null (no audio, no play button, no transcription button)
    	stale transcription or not downloaded yet (Check machine transcription, or Re-check)
    	fresh transcription (Import)
    */
    function promptUserImportTranscription(){
    	if(document.getElementById('importButton').value=="Import"){
    		Android.askUserIfImportJS(document.getElementById('markItUp').value); //will open the _server.srt and ask the user if they want to import it, it will put it in the markitup.
    		document.getElementById('importButton').value='Re-check'; // show import button
    	}else{
    		Android.downloadTranscriptionFromServerJS(document.getElementById('markItUp').value); //will download the transcrition from server.
    		document.getElementById('importButton').value='Checking...'; // show import button
    	}
    }
    function displayPlayButton(){
    	if (hasAudio == true){
    		//do nothing, it is already visible
    	}else{
    		hasAudio = true;
    		document.getElementById('playButton').style.visibility='visible'; // hide play button
    		document.getElementById('importButton').style.visibility='visible'; // show import button
    		
    		/*
    		var playButtn  = document.createElement("input");
        	playButtn.setAttribute("type","button");
        	playButtn.setAttribute("id","playButton");
        	playButtn.setAttribute("value","Play");
        	playButtn.setAttribute("onClick","playPauseAudioController()");
        	document.getElementById("buttonArea").appendChild(playButtn);
        	*/
    	}
    }
    
    function displayImportButton(){
    	doit = Android.hasFreshTranscriptionJS();
    	if (doit == "true" ){
    		freshTranscription = true;
    		document.getElementById('importButton').style.visibility='visible'; // show import button
    		document.getElementById('importButton').value='Import'; // show import button
    	}else{
    		freshTranscription = false;
    		document.getElementById('importButton').style.visibility='visible'; // show import button
    		document.getElementById('importButton').value='Re-check'; // show import button
    	}
    	var doit = Android.hasAudioFileJS();
    	if (doit == "false" ){
    		document.getElementById('importButton').style.visibility='hidden'; // hide import button
    	}
    	
    }
    
    /* Additional Interface contents:
		Android.getTimeRecordedJS();
	    Android.showToastJS(toast);
	    Android.getAudioResultsFileStatusJS(); TODO?
	    Android.downloadTranscriptionFromServerJS();
	    Android.askUserIfImportJS(document.getElementById('markItUp').value); //will open the _server.srt and ask the user if they want to import it, it will put it in the markitup.
	*/
    
    
    function readTTSPost(){
    	Android.readToTTSJS("This is what your blog entry says... "+document.getElementById('markItUp').value);
    }
    function deletePost(){
    	Android.deletePostJS(document.getElementById('f-title').value,document.getElementById('markItUp').value,document.getElementById('post-labels').value);
    }
    function saveButton(){
    	readTTSPost();
    	Android.zeroOutParentResultFileJS();
    	hasAudio=false;
    	document.getElementById('playButton').style.visibility='hidden'; // hide play button
    	Android.savePostJS(document.getElementById('f-title').value,document.getElementById('markItUp').value,document.getElementById('post-labels').value);
    }
    function savePostToDB(){
    	Android.savePostJS(document.getElementById('f-title').value,document.getElementById('markItUp').value,document.getElementById('post-labels').value);
    }
    function savePostAsSelfToDB(){
    	Android.savePostAsSelfToDBJS(document.getElementById('f-title').value,document.getElementById('markItUp').value,document.getElementById('post-labels').value);
    }
    function savePostToState(){
    	Android.saveStateJS(document.getElementById('f-title').value,document.getElementById('markItUp').value,document.getElementById('post-labels').value);
    }
    function publishPostToDB(){
    	Android.publishPostJS(document.getElementById('f-title').value,document.getElementById('markItUp').value,document.getElementById('post-labels').value);
    }
    function fillFromAndroidActivity(){
    	document.getElementById('f-title').value= Android.fetchPostTitleJS();
    	document.getElementById('markItUp').value= Android.fetchPostContentJS();
    	document.getElementById('post-labels').value= Android.fetchPostLabelsJS();
    	var doit = Android.hasAudioFileJS();
    	if (doit == "true" ){
    		displayPlayButton();
    		document.getElementById('recordButton').value="New Dictation";
    	}
	   	displayImportButton();
    }
    function fillPostContentFromAndroidActivity(){
    	document.getElementById('markItUp').value=Android.fetchPostContentJS();
    	displayImportButton();
    	
    }
    function checkRecordingNow(){
    	if (Android.getValueRecordingNowJS() == 1){
    		document.getElementById('recordButton').value="Stop Dictation";
    	}else{
    		document.getElementById('recordButton').value="New Dictation";
    	}
    }
    /*
	Ask server for transcription file
	*/
	function UrlExists(url)
	{
	    var http = new XMLHttpRequest();
	    http.open('HEAD', url, false);
	    http.send();
	    return http.status!=404;
	}
    function downloadTranscription(){
    	Android.downloadTranscriptionFromServerJS(document.getElementById('markItUp').value);
    }
    var queryServerIfTranscriptionIsReady = function(){
    	//http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
    	//http://stackoverflow.com/questions/3973933/jquery-load-callback-function
		//jQuery.post( url, [data], [success(data, textStatus, jqXHR)], [dataType] );
		$('#fileStatusArea').load(Android.getTranscriptionRequestURLJS(),function(data){
		    // use the data param
		    // e.g. $(data).find('#icc10n')
			var response = JSON.parse(data);
			//document.getElementById('fileStatusArea').value  = "";
			if (response["status"] == null && "true" === Android.hasAudioFileJS()){
				//there is no audio file on the server, try to send it (again) maybe the user will be on wifi
				Android.sendDictationToServerJS(document.getElementById('markItUp').value);
			}
			/*
			this will send a client update each time the user loads the edit blog entry, until the server status changes (the next status should be nothing fresh.
			*/
			if (response["status"] == "dictation received"){
				Android.sendClientUpdateJS(document.getElementById('markItUp').value);
			}
			/*
			If the server has a fresh transcription for the user, try to download it (and import it into the contents)
			*/
			if (response["status"] == "transcription fresh"){
				Android.downloadTranscriptionFromServerJS(document.getElementById('markItUp').value);
			}
			/*
			If the server hasnt changed anything, dont do anything
			*/
			if (response["status"] == "transcription nothing fresh"){
				//
			}
			$('#fileStatusArea').hide();
		});
		
    }
	/*Dictation ->Transcription lifecycle
	null --> dictation recieved --> transcription nothing fresh -->
								     \					      ^	
				                     --> transcription fresh /
	*/
	//after loading the page try this.
	var  processTranscriptionServerResponse = function(){
		var response = JSON.parse(document.getElementById('fileStatusArea').value);
		//document.getElementById('fileStatusArea').value = "";
		
		if (response["status"] == "dictation received"){
			Android.sendClientUpdateJS(document.getElementById('markItUp').value);
		}else{
			Android.downloadTranscriptionFromServerJS(document.getElementById('markItUp').value);
		}
		/*
		if (response["status"] == null && Android.hasAudioFileJS()){
			//there is no audio file on the server, try to send it (again) maybe the user will be on wifi
			Android.sendDictationToServerJS(document.getElementById('markItUp').value);
		}
		/*
		this will send a client update each time the user loads the edit blog entry, until the server status changes (the next status should be nothing fresh.
		
		if (response["status"] == "dictation received"){
			Android.sendClientUpdateJS(document.getElementById('markItUp').value);
		}
		/*
		If the server has a fresh transcription for the user, try to download it (and import it into the contents)
		
		if (response["status"] == "transcription fresh"){
			Android.downloadTranscriptionFromServerJS(document.getElementById('markItUp').value);
		}
		/*
		If the server hasnt changed anything, dont do anything
		
		if (response["status"] == "transcription nothing fresh"){
			//do nothing
		}
		*/
    }

	
	function regexReplace(){
		/*TODO allow user to do regex replacements in blog contents, log to frequent rules to automate if they want
		*/
	}
</script>

<div id="container">

<table  id="titles"  >
<tbody><tr><td><label for="f-title">Title:</label></td></tr><tr>
<td width="80%">
	<input type="text" name="title" value="" id="f-title" tabindex="1" class="text" maxlength="150" dir="ltr" size="48"></div></td></tr>
<tr><td>
	<div id="label-directions"><b>Labels for this post:</b><br>
<span style="color: #555">e.g. <b>scooters, vacation, fall</b></span></div>
</td></tr>
<tr><td ><input type="text" name="postLabels" value="" class="text" size="48" id="post-labels" tabindex="2" dir="ltr"></td></tr>
</tbody></table>
<div id="fileStatusArea">
</div>
	<textarea id="markItUp" >
Type your text here. You can select text and then hit the button you want, or you can hit the button type and then hit the button to turn it off. You can use new paragraphs:

&lt;p&gt;&lt;strong&gt;bold&lt;/strong&gt;

&lt;h3&gt;and headings&lt;/h3&gt;

 &lt;p&gt;We are using Jay Salvart's Markitup to give you some approximation of wysiwyg editing. Normal wysiwyg editors don't work in embedded Android webview at the moment. With Jay's Markitup you to turn any textarea into a markup editor. Html, Textile, Wiki Syntax, Markdown, BBcode or even your own markup system can be easily implemented. So you can design your own markup system that makes blogging easier for you.&lt;/p&gt;
</textarea>



</p>
</body>
</html>
